package org.zjt.java.demo.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import javax.servlet.http.HttpServletRequest;


@ControllerAdvice(annotations={Controller.class})
public class ErrorViewResoler extends ResponseEntityExceptionHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(ErrorViewResoler.class);

    
	@ExceptionHandler
    public ModelAndView handleControllerException(HttpServletRequest request, Throwable ex) {
		HttpStatus status=getStatus(ex);
		if (HttpStatus.FORBIDDEN.equals(status)){
            ModelAndView mv=new ModelAndView("common/error_page_403");
            LOGGER.error("Throwable:{}",ex );
            return mv;
        }
        String errorMsg=ex.getMessage()==null ? "NullPointerException:"+status: ex.getMessage();
        ModelAndView mv=new ModelAndView("common/error_page");
        LOGGER.error("Throwable:{}",ex );
        mv.addObject("errorMsg",errorMsg);
        return mv;
    }

    private HttpStatus getStatus(Throwable ex) {
	    if (ex == null)
	        return HttpStatus.INTERNAL_SERVER_ERROR;
	    if (ex instanceof AccessDeniedException)
	        return HttpStatus.FORBIDDEN;
	    return null;
    }

}
